﻿import urllib2
from urlparse import urlparse as up
from base64 import encodestring

LOGIN = "wenhao"
PASSWD = "you'llneverGUESS"
URL = "http://localhost"

#具体方法的功能不理解
def  handler_version(url):
    
    hdlr = urllib2.HTTPBasicAuthHandler()
    hdlr.add_password('Archives', up(url)[1],LOGIN,PASSWD)
    opener = urllib2.build_opener(hdlr)
    urllib2.install_opener(opener)
    return url

def request_version(url):
    
    req = urllib2.Request(url)
    b64str = encodestring('%s:%s' %(LOGIN, PASSWD))[:-1]
    print 'b64str = %s' %b64str
    req.add_header("Authorization", "Basic %s" %b64str)
    return req

for funcType in ('handler', 'request'):
    print '*** Using %s:' %funcType.upper()
    url = eval('%s_version' %funcType)(URL) #这一句循环的调用方法，（URL）为传的参数

    print 'url %s' %url
    f = urllib2.urlopen(url)
    print f.readline()
    f.close()
